package com.scut.fy.admin.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scut.fy.admin.mapper.SysUserMapper;
import com.scut.fy.admin.model.entity.SysUser;
import com.scut.fy.admin.model.vo.UserVo;
import com.scut.fy.admin.service.UserService;
import com.scut.fy.common.core.constant.FySaTokenConstant;
import com.scut.fy.common.core.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 用户注册服务
 *
 * @author JY
 * @version 1.0
 * @date 2021/9/15
 */
@Service
public class UserServiceImpl implements UserService {
    private static Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    /**
     * 密码过期后自动延后的日期
     */
    private static final int PWD_PLUS_DAY = 90;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public long insertUser(UserVo userVo) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userVo, sysUser);
        // 密码用md5加盐加密
        sysUser.setPassword(
                SaSecureUtil.md5BySalt(
                        SecureUtil.md5(userVo.getPassword()),
                        SecureUtil.md5(FySaTokenConstant.MD5_SALT)));
        // 密码90天后过期
        sysUser.setPwdEndTime(LocalDateTime.now().plusDays(PWD_PLUS_DAY));
        // 电话，邮箱等用aes加密
        sysUser.setPhone(SaSecureUtil.rsaEncryptByPublic(FySaTokenConstant.AES_STRING, sysUser.getPhone()));
        sysUser.setEmail(SaSecureUtil.rsaEncryptByPublic(FySaTokenConstant.AES_STRING, sysUser.getEmail()));

        // 把用户的状态设置为正常
        sysUser.setDelFlag("6");
        sysUser.setStatus("6");

        sysUser.setCreateTime(LocalDateTime.now());
        sysUser.setUpdateTime(LocalDateTime.now());
        return (long) sysUserMapper.insert(sysUser);
    }

    @Override
    public long updateUser(UserVo userVo) {
        Assert.notNull(userVo.getUserId(), "用户id不能为空");
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userVo, sysUser);
        if (userVo.getPassword() != null) {
            // 密码用md5加盐加密
            sysUser.setPassword(
                    SaSecureUtil.md5BySalt(
                            SecureUtil.md5(userVo.getPassword()),
                            SecureUtil.md5(FySaTokenConstant.MD5_SALT)));
        }
        if (userVo.getPhone() != null) {
            // 电话，邮箱等用aes加密
            sysUser.setPhone(SaSecureUtil.rsaEncryptByPublic(FySaTokenConstant.AES_STRING, sysUser.getPhone()));
        }
        if (userVo.getEmail() != null) {
            sysUser.setEmail(SaSecureUtil.rsaEncryptByPublic(FySaTokenConstant.AES_STRING, sysUser.getEmail()));
        }
        sysUser.setUpdateTime(LocalDateTime.now());
        return (long) sysUserMapper.updateById(sysUser);
    }

    @Override
    public boolean updateUserPwdTime(long userId) {
        try {
            SysUser sysUser = sysUserMapper.selectById(userId);
            LocalDateTime localDateTime = LocalDateTime.now();
            sysUser.setPwdEndTime(localDateTime.plusDays(PWD_PLUS_DAY));
            sysUser.setUpdateTime(localDateTime);
            sysUserMapper.updateById(sysUser);
            log.error("密码延期{}天成功", PWD_PLUS_DAY);
            return true;
        } catch (Exception e) {
            log.error("更新密码有效期失败");
            return false;
        }
    }

    @Override
    public UserVo getUser(long userId) {
        UserVo userVo = new UserVo();
        SysUser sysUser = sysUserMapper.selectById(userId);
        BeanUtils.copyProperties(sysUser, userVo);
        // 电话，邮箱等先用aes解密，然后再脱敏
        userVo.setPhone(
                DesensitizedUtil.mobilePhone(
                        SaSecureUtil.rsaDecryptByPrivate(
                                FySaTokenConstant.AES_STRING, sysUser.getPhone())));
        userVo.setEmail(
                DesensitizedUtil.email(
                        SaSecureUtil.rsaDecryptByPrivate(
                                FySaTokenConstant.AES_STRING, sysUser.getEmail())));

        return userVo;
    }

    /**
     * 获取用户信息
     * TODO
     * @param userIds@return
     */
    @Override
    public Page<UserVo> getUser(Page<Long> userIds) {
        return null;
    }

    @Override
    public UserVo checkUserPwd(String userName, String password) {
        Assert.notNull(userName, "用户名不能为空");
        Assert.notNull(password, "用户密码不能为空");
        String pwd = SaSecureUtil.md5BySalt(
                        SecureUtil.md5(password),
                        SecureUtil.md5(FySaTokenConstant.MD5_SALT));
        // 先查数据库里面有没有这个用户的数据
        SysUser sysUser = sysUserMapper.selectOne(
                new QueryWrapper<SysUser>().lambda().eq(SysUser::getUserName, userName));
        if (sysUser == null) {
            log.info("{}：用户不存在", userName);
            return null;
        }
        // 判断密码是否正确
        if (pwd.equals(sysUser.getPassword())) {
            log.info("密码正确");
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(sysUser, userVo);
            return userVo;
        } else {
            log.info("密码错误，或者密码没有md5加密");
            return null;
        }
    }

}
